$(function() {
//Declare variable
var 	tips = $( ".validateTips" ),
		button_name="",
		url="a_cust_service.php", 
		ID="", // Customer ID
		BranchSaleID='',
		rowSelect="",
		SID='',
		list={};
		 
		ID=$("#custid").val();
		//Load First page
		LoadData(1,true,ID);
	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan=10 class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};
		
		//b=false , don't gennerate paging
		function LoadData(page,b,id){
			
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			 //Post 			
			 $.post(url,{'m':'info','id':id} , function(data){
			 //alert(data);
				var ar = eval('('+data+')');
				$("#iCode").attr('innerHTML',(ar['Code']));
				$("#iName").attr('innerHTML',(ar['FirstName'] + ' ' + ar['LastName']));
				$("#iBirthday").attr('innerHTML',(ar['BirthDay']));
				$("#iAddress").attr('innerHTML',(ar['Address']));
				$("#iLastAccess").attr('innerHTML',(ar['LastedAccess']));	
				$("#iEmail").attr('innerHTML',(ar['Email']));							
				$("#iTele").attr('innerHTML',(ar['Telephone']));				
			});	
			 
			$.post(url,{'m':'service','id':id},function(data){
			 
				var obj=eval("(" + data + ")");
				hideLoader();
			 	$( "#resultData tbody tr" ).remove();
				 $( "#rowCount" ).attr('innerHTML',obj['rows']);
				 $( "#resultData tbody" ).append(obj['data']);
			
				//set page
				if (b){
				 
					var p="<ul>";
					for (var i=parseInt(obj['totalpage']);i >0 ;i--){
						p = p +'<li id="'+i+'">'+i+'</li>';
					}
					p = p+"</ul>";
					$("#paging_button ul").remove();
					$("#paging_button").append(p);
					 
				}
				$("#"+page).css({'background-color' : '#006699'});
			});
		}
 
	$("#btnBack").live('click',function(){
		//alert('d');
		//history.back(-1);
		$("#Act").submit();
	});
		// Set icon
	// Search button on main screen
	$("#btnAddTimes").button({
		icons:{
		 primary: "ui-icon-circle-plus"
		}
	});	

	$("#btnAddTimes").click(function(){
		//alert(BranchSaleID + ' '  + $("#cBranchID").val());
		//Check different branch
		if( $("#cBranchID").val()!= BranchSaleID){
			$("#dialog-confirm" ).dialog("open" );
			$("#dialog-confirm" ).dialog("option","buttons",{
				"OK":function(){
					if ($("#appby").val() !=""){
						updateAccessService($("#appby").val());
						$( this ).dialog( "close" );
						return true;
					}else{
						alert('Please input Approved name');
						return false;
					}
					
				},
				"Close":function(){
					$( this ).dialog( "close" );
				}
			});
		}else{
			updateAccessService("");
		}
		
	});
	
	$("input[name=txtUsed]").live('keypress',function(e){
			
			if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) && e.which!=46){
				return false;
			}
	});
		
	$("input[name=txtUsed]").live('blur',function(event){		
			var iInput = $(this).val();
			var rowSelect = $(this).parent().parent();
			var id = rowSelect.find("td").eq(0).html();
			var iRemain= new Number(rowSelect.find("td").eq(4).html().replace(',',''));
			if (iInput==""){
				iInput=0;
				 $(this).val(0);
			}
			if ( (iInput > iRemain)){
				alert('Invalid input amount.');
				$(this).focus().select(); 
			}else{
			
				if (iInput > 0){
					$.ajax({
						type: 'POST',
						cache: false,
						url: url,
						data: {'id':id,'amt':iInput,'m':'chkstock'},
						success: function(data){
							//alert(data);
							var obj=eval("("+data+")");
							if (obj['rows']=='9999'){
								alert( 'The product : "' + eval("("+obj['data']+")")['ProductName'] + '" is not enough.');
								$(this).focus().select(); 
								return false;
							}
							return;
						}
					});
				}
			}
	});
	
	$("#btnUpdate").live('click',function(){
		var cid="";
		var camt="";
		$("#dialog-Update").dialog({'title':"Update Service"});
		$("#dialog-Update" ).dialog("open" );
		$("#dialog-Update" ).dialog("option","buttons",{
			"Save":function(){
			
				var listAmt=[];
				
				$( "#tbServiceAllInfo tbody tr").each(function(){
					
					var amt = $(this).find("input[name=txtUsed]").val(); 
					var csid = $(this).find("td").eq(0).html();
					if (amt != '0'){
						cid += csid + '|' ;
						camt += amt + '|' ; 
						listAmt.push({'csid':csid,'amount':amt	});
					}else{
						//cid += csid + '|' ;
					}
				});
				
				if (cid  != ""){
					$.ajax({
						type: 'POST',
						cache: false,
						url: url,
						data: {'list':listAmt,'m':'updateall'},
						success: function(data){
							LoadData(1,true,ID);
							$("#dialog-Update" ).dialog( "close" );
		 	 
							newwindow=window.open('cc_print.php?c='+ID+'&i='+cid+'&a='+camt,'','height=450px,width=350px');
							if (window.focus) {newwindow.focus()}	
							
						}
					});	
				}else{
					alert('กรุณากรอกจำนวน');
					return false;
				}
				
			},"Close":function(){
				$( this ).dialog( "close" );
			}
		});
	});
 
	function updateAccessService(appBy){

		var used = $( "#tbServiceInfo tbody tr" ).find("td").eq(3).html();
		var remain = $( "#tbServiceInfo tbody tr" ).find("td").eq(4).html();
		if (remain=='0'){
			return false;
		}
		//ID -> CustID
		//SID -> Service ID
		$.post(url,{'m':'add',
					'id':ID, 
					'sid':SID,
					'approvedby':appBy,
					'remark':$("#Remark").val() 
					}
			,function(data){
			 // alert(data);
				 
				var obj=eval("("+data+")");
			 
				if (obj['rows']=='9999'){
					alert( 'The product : "' + eval("("+obj['data']+")")['ProductName'] + '" is not enough.');
					return false;
					
				}else{
					$( "#tbServiceHistory tbody tr" ).remove();
					$( "#tbServiceHistory tbody" ).append(obj['data']);		
					
					$( "#tbServiceInfo tbody tr" ).find("td").eq(3).html(parseInt(used)+1);
					$( "#tbServiceInfo tbody tr" ).find("td").eq(4).html(parseInt(remain)-1);
					rowSelect.find("td").eq(5).html(obj['date']);
					rowSelect.find("td").eq(8).html(parseInt(remain)-1);			
					
					list[obj['csid']]=SID;
					
					return true;
				}
			});
	}
	$(".btnRemove").live('click',function(){
		var rid=$(this).parent().parent().find("td").eq(1).html();
		var Delamt= $(this).parent().parent().find("td").eq(6).html(); // amt
		var amt= new Number(Delamt); // amt
	
		var used = $( "#tbServiceInfo tbody tr" ).find("td").eq(3).html();
		var remain = $( "#tbServiceInfo tbody tr" ).find("td").eq(4).html();
		
		delete list[rid];
		
		$( "#dialog-confirmRemove" ).dialog("open");
		$("#dialog-confirmRemove" ).dialog("option","buttons",{
			"OK":function(){
				//alert(rid);
				$.post(url,
						{'m':'del',
						'rid':rid,
						'id':SID,
						'amt':Delamt
						}
						,function(data){
						  
							var obj=eval("("+data+")");
							$( "#tbServiceHistory tbody tr" ).remove();
							$( "#tbServiceHistory tbody" ).append(obj['data']);		
							
							$( "#tbServiceInfo tbody tr" ).find("td").eq(3).html(parseInt(used)-amt);
							$( "#tbServiceInfo tbody tr" ).find("td").eq(4).html(parseInt(remain)+amt);
						
							rowSelect.find("td").eq(8).html(parseInt(remain)+amt);
						});
						
				$("#dialog-confirmRemove" ).dialog( "close" );
			},
			"Close":function(){
				$( this ).dialog( "close" );
			}
		});

	});
	
	$(".btnUsed").live('click',function(){
		rowSelect = $(this).parent().parent();
		list=[];
		SID=rowSelect.find("td").eq(1).html();
		
		BranchSaleID = rowSelect.find("td").eq(2).html();
		 
		var courseName = rowSelect.find("td").eq(3).html();
		var branchName = rowSelect.find("td").eq(4).html();
		var Total = rowSelect.find("td").eq(7).html();
		var Remain = rowSelect.find("td").eq(8).html();
		
		$( "#tbServiceInfo tbody tr" ).remove();
 
		var table="<tr  style='height:25px;color:#ac0937;'><td align='center'>"+ courseName +"</td>"
				+"<td align='center'>"+ branchName +"</td>"
				+"<td align='center'>"+ Total +"</td>"
				+"<td align='center'>"+ String( parseInt(Total)-parseInt(Remain) )+"</td>"
				+"<td align='center'>"+ Remain +"</td></tr>";
				
		 $( "#tbServiceInfo tbody" ).append(table);
		
		$.post(url,{'m':'detail','id':SID},function(data){
			
			var obj=eval("("+data+")");
			
			$( "#tbServiceHistory tbody" ).append(obj['data']);
			
		});
		
		$("#dialog-form").dialog({'title':"POS Service"});
		$("#dialog-form" ).dialog("open" );
		$("#dialog-form" ).dialog("option","buttons",{
			"Close":function(){
				$( this ).dialog( "close" );
				var idlist;
				var totalCourse=0;
				for (prop in list) {
					totalCourse++;
					idlist = list[prop];
				  }		 
				if (totalCourse > 0) {
					newwindow=window.open('cc_print.php?c='+ID+'&i='+idlist+'|&a='+totalCourse+'|','','height=450px,width=350px');
					if (window.focus) {newwindow.focus()}	
				}
				
			}
		});
	});
	
	$("#paging_button li").live('click',function(){
		$("#paging_button li").css({'background-color' : ''});
 		LoadData(this.id,false,ID);

	});
	// Close Dialog 
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
		//Form customer Search
			//Confirm Dialog
	$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:200,
			width:400,
			zIndex:9999,
			autoOpen: false,
			modal: true , 
			open :function(){
				$("#appby").val('');
			}
	});	
	$( "#dialog-confirmRemove" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
	});	
		
	
	$( "#dialog-Update" ).dialog({
		autoOpen: false,
		resizable:false,
		height: 360,
		zIndex:9999,
		width: 480,
		modal: true,
		open: function() { 
			$.post(url,{'m':'getServiceUpdate','id':ID},function(data){
				var obj=eval("(" + data + ")");
				$( "#tbServiceAllInfo tbody tr" ).remove();
				$( "#tbServiceAllInfo tbody" ).append(obj['data']);
			});
		},
		close: function() {
			$( "#tbServiceAllInfo tbody tr" ).remove();
		}
	});	
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		resizable:false,
		height: 500,
		zIndex:9999,
		width: 650,
		modal: true,
		open: function() { 
			$("#Remark").val('');
			list=[];
			$( "#tbServiceHistory tbody tr" ).remove();
			//allFields.val( "" );
			//}
		},
		close: function() {
			//allFields.attr("readonly","");
			//allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
});
	